package com.weilive.core.netty.http;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.weilive.core.utils.ClassUtils;

public class HttpServletManager {

	private static final Logger log = LoggerFactory.getLogger(HttpServletManager.class);
	
	private static final HashMap<String, HttpServlet> servlets = new HashMap<String, HttpServlet>();
	
	public static void loadBySearch(String pkgName) {
		for (Class<?> c : ClassUtils.getClassList(pkgName, true, HttpServlet.class)) {
			HttpServlet servlet;
			try {
				servlet = (HttpServlet)c.newInstance();
				servlets.put(servlet.getServletPath(), servlet);
				log.info("===> load http servlet:"+ servlet.getServletPath());
			} catch (Exception e) {
			}
		}
	}
	
	public static void loadBySpring(ApplicationContext context) {
		for (HttpServlet servlet : context.getBeansOfType(HttpServlet.class).values()) {
			servlets.put(servlet.getServletPath(), servlet);
			log.info("===> load http servlet:"+ servlet.getServletPath());
		}
	}
	
	public static void registerServlet(HttpServlet servlet) {
		if (servlet != null) {
			servlets.put(servlet.getServletPath(), servlet);
			log.info("===> register http servlet:"+ servlet.getServletPath());
		}
	}
	
	public static HttpServlet getServlet(String uri) {
		int pos = uri.indexOf('?');
		return servlets.get(pos > 0 ? uri.substring(0, pos) : uri);
	}
}
